package com.zy.test.config;


import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.instrument.async.LazyTraceThreadPoolTaskExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author MissZhou
 * 线程池配置类-具体参数可结合测试同事接口压测的数据进行设置线程池参数
 */
@Configuration
public class ThreadPoolConfiguration {

    @Autowired
    private static BeanFactory beanFactory;

    @Bean("monitorThreadPoolTaskExecutor")
    public static LazyTraceThreadPoolTaskExecutor monitorThreadPoolTaskExecutor(){

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //设置线程池固定线程数
        threadPoolTaskExecutor.setCorePoolSize(10);
        //设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(20);
        //设置任务队列数量
        threadPoolTaskExecutor.setQueueCapacity(100);
        //设置线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //设置是否允许超时
        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
        //设置线程名称前缀-方便后期问题排查
        threadPoolTaskExecutor.setThreadNamePrefix("monitor-thread-pool-");
        //设置拒绝策略-默认抛出异常
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //设置关闭线程池时必须完成所有任务才销毁对应的bean
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);

        //初始化线程池
        threadPoolTaskExecutor.initialize();

        return new LazyTraceThreadPoolTaskExecutor(beanFactory,threadPoolTaskExecutor);
    }
}
